package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wgg sync.WaitGroup

func worker3(ctx context.Context) {
LOOP:
	for {
		fmt.Println("db is connecting")
		time.Sleep(10 * time.Millisecond) //假设连接耗费10毫秒
		select {
		case <-ctx.Done():
			break LOOP
		default:
		}
	}
	fmt.Println("woker done")
	wgg.Done()
	return
}
func main() {
	// 设置一个50毫秒的超时
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)

	wgg.Add(1)
	go worker3(ctx)
	time.Sleep(time.Second)
	cancel() //这里不能用defer 因为用了的话上面的函数就永远不会break
	wgg.Wait()
	fmt.Println("over")
}
